package com.situ.mall.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiNiuUtil {
    private static final String accessKey = "8ZshZeJZYTPt13gNbytTbMHhVJ0f_ut6W9nWmJSX";
    private static final String secretKey  = "aklJzwDxxNKmEiSWrtEpbcz7Ak5JA5mVjdKbgdTb";
    private static final String bucket  = "java2007";

    private static Auth auth;
    private static UploadManager uploadManager;

    static {
        // 构造一个带指定Zone对象的配置类
        auth = Auth.create(accessKey, secretKey);
        Configuration cfg = new Configuration(Region.region1());
        // ...其他参数参考类注释
        uploadManager = new UploadManager(cfg);
    }

    /*
     * 上传单张图片，返回值是图片在七牛服务器上的名字
     */
    public static String uploadImage(byte[] buffer) {
        String key = null;
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(buffer, key, upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            // key代表图片的名字
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                // ignore
            }
        }
        return "";
    }
}
